package com.substation.utils;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;

import java.util.Timer;
import java.util.TimerTask;



/**
 * 倒计时类
 *
 * @author wangbing
 */
public class CountDown {
    private static int time;
    private static Timer timer;
    private static Button timeTv;
    private static Context context;

    /**
     * @param startTime -倒计时开始时间
     */
    public static void startBtTime(final int startTime, final Context context, final Button timeTv) {
        CountDown.timeTv = timeTv;
        CountDown.context = context;
        cancleTimer();
        time = startTime;
        timer = new Timer();
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                time--;
                Message msg = new Message();
                msg.obj = time;
                handler.sendMessage(msg);
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

    private static Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (Integer.parseInt(msg.obj.toString()) == 0) {
                cancleTimer();
            }
            switch (Integer.parseInt(msg.obj.toString())) {
                case 0:
                    timeTv.setText("获取验证码");
                    timeTv.setClickable(true);
                    timeTv.setTextColor(Color.RED);
                    break;

                default:
                    timeTv.setText(msg.obj.toString() + "秒后重试");
                    timeTv.setTextColor(Color.WHITE);
                    timeTv.setClickable(false);
                    break;
            }
        }

        ;
    };

    /**
     * 回收内存
     */
    public static void cancleTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}
